<template>
  <el-row :gutter="20">
    <el-col :span="24">
      <el-card>
        <div class="mb-4" style="margin-bottom: 20px;">
          <el-button type="success" plain @click="insertAdminShow = true;">新增</el-button>
        </div>
        <el-table :data="adminList" style="width: 100%" height="250">
          <el-table-column fixed prop="aid" label="ID" width="70" style="" />
          <el-table-column prop="aavatar" label="头像" width="100">
            <template #default="scope">
              <el-avatar shape="square" :size="50" :src="'http://localhost:8080/upload/' + scope.row.aavatar" />
            </template>
          </el-table-column>
          <el-table-column prop="aname" label="用户名" width="100" />
          <el-table-column prop="aage" label="年龄" width="100" />
          <el-table-column prop="agender" label="性别" width="100" />
          <el-table-column prop="acontact" label="联系方式" width="100" />
          <el-table-column prop="permissions" label="身份" width="100" />

          <el-table-column label="操作" width="200">
            <template #default="scope">

              <el-button size="small" type="primary" @click="showUpdateAdmin(scope.row.aid)">
                <el-icon>
                  <Edit />
                </el-icon>修改
              </el-button>

              <el-popconfirm title="你确定要删除该用户吗?" confirm-button-text="确认" cancel-button-text="取消" width="200px"
                @confirm="delectByAid(scope.row.aid)">

                <template #reference>
                  <el-button size="small" type="danger">
                    <el-icon>
                      <Delete />
                    </el-icon>删除
                  </el-button>
                </template>

              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-col>
  </el-row>
  <el-row :gutter="20">
    <el-col :span="24">
      <el-card>
        <div class="mb-4" style="margin-bottom: 20px;">
          <el-button type="success" plain @click="insertBorrowShow = true;">新增</el-button>
        </div>
        <el-table :data="borrowList" style="width: 100%" height="250">
          <el-table-column fixed prop="boid" label="ID" width="70" />
          <el-table-column prop="admin.aname" label="用户" width="100" />
          <el-table-column prop="book.bname" label="书籍" width="100" />
          <el-table-column prop="boout" label="借出时间" width="100" />
          <el-table-column prop="bostill" label="归还时间" width="100" />
          <el-table-column prop="bodeposit" label="押金" width="100" />
          <el-table-column prop="bostate" label="借阅状态" width="100">
            <template #default="scope">
              <el-tag type="primary" v-if="scope.row.bostate == 1">借阅中</el-tag>
              <el-tag type="info" v-else>已归还</el-tag>
            </template>
          </el-table-column>



          <el-table-column fixed="right" label="操作" width="200">
            <template #default="scope">

              <el-button size="small" type="primary" @click="showUpdateBorrow(scope.row.boid)">
                <el-icon>
                  <Edit />
                </el-icon>修改
              </el-button>

              <el-popconfirm title="你确定要删除该部门吗?" confirm-button-text="确认" cancel-button-text="取消" width="200px"
                @confirm="delectByBoid(scope.row.boid)">
                <template #reference>
                  <el-button size="small" type="danger">
                    <el-icon>
                      <Delete />
                    </el-icon>删除
                  </el-button>
                </template>

              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-col>
  </el-row>

  <!-- 添加用户对话框开始 -->
  <el-dialog v-model="insertAdminShow" title="添加用户" width="500">
    <el-form>
      <el-form-item label="用户" label-width="20%">
        <el-input v-model="adminAdd.aname" autocomplete="off" />
      </el-form-item>
      <el-form-item label="年龄" label-width="20%">
        <el-input v-model="adminAdd.aage" autocomplete="off" />
      </el-form-item>

      <el-form-item label="性别" label-width="20%">
        <el-radio-group v-model="adminAdd.agender">
          <el-radio value="男" size="large">男</el-radio>
          <el-radio value="女" size="large">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="联系方式" label-width="20%">
        <el-input v-model="adminAdd.acontact" autocomplete="off" />
      </el-form-item>

      <el-form-item label="身份" label-width="20%">
        <el-input v-model="adminAdd.permissions" autocomplete="off" />
      </el-form-item>


      <el-form-item label="头像" label-width="20%">
        <el-upload class="avatar-uploader" action="http://localhost:8080/admin/upload/" name="pic" :headers="headers"
          :show-file-list="false" :on-success="handleAvatarSuccessAdd" :before-upload="beforeAvatarUploadAdd">
          <img v-if="imageUrlAdd" :src="imageUrlAdd" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="insertAdminRemove">取消</el-button>
        <el-button type="primary" @click="addAdmin();">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--添加用户的对话框结束-->

  <!-- 添加借阅表对话框开始 -->
  <el-dialog v-model="insertBorrowShow" title="添加用户" width="500">
    <el-form>

      <el-form-item label="用户ID" label-width="20%">
        <el-input v-model="borrowAdd.aid" autocomplete="off" />
      </el-form-item>

      <el-form-item label="书籍ID" label-width="20%">
        <el-input v-model="borrowAdd.bid" autocomplete="off" />
      </el-form-item>

      <el-form-item label="借出日期" label-width="20%">
        <el-input v-model="borrowAdd.boout" autocomplete="off" />
      </el-form-item>

      <el-form-item label="归还日期" label-width="20%">
        <el-input v-model="borrowAdd.bostill" autocomplete="off" />
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="insertBorrowRemove">取消</el-button>
        <el-button type="primary" @click="BorrowAdd();">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--添加借阅表的对话框结束-->


  <!-- 修改用户对话框开始 -->
  <el-dialog v-model="updateAdminShow" title="修改用户" width="500">
    <el-form>
      <el-form-item label="用户" label-width="20%">
        <el-input v-model="adminUpdate.aname" autocomplete="off" />
      </el-form-item>
      <el-form-item label="年龄" label-width="20%">
        <el-input v-model="adminUpdate.aage" autocomplete="off" />
      </el-form-item>

      <el-form-item label="性别" label-width="20%">
        <el-radio-group v-model="adminUpdate.agender">
          <el-radio value="男" size="large">男</el-radio>
          <el-radio value="女" size="large">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="联系方式" label-width="20%">
        <el-input v-model="adminUpdate.acontact" autocomplete="off" />
      </el-form-item>

      <el-form-item label="身份" label-width="20%">
        <el-input v-model="adminUpdate.permissions" autocomplete="off" />
      </el-form-item>

      <el-form-item label="头像" label-width="20%">
        <el-upload class="avatar-uploader" action="http://localhost:8080/admin/upload/" name="pic" :headers="headers"
          :show-file-list="false" :on-success="handleAvatarSuccessUpdate" :before-upload="beforeAvatarUploadUpdate">
          <img v-if="imageUrlUpdate" :src="imageUrlUpdate" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateAdminRemove">取消</el-button>
        <el-button type="primary" @click="updateAdmin();">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--修改用户的对话框结束-->

  <!-- 修改借阅记录对话框开始 -->
  <el-dialog v-model="updateBorrowShow" title="修改借阅记录" width="500">
    <el-form>

      <el-form-item label="用户ID" label-width="20%">
        <el-input v-model="BorrowUpdate.aid" autocomplete="off" aria-label="uname" />
      </el-form-item>

      <el-form-item label="书籍ID" label-width="20%">
        <el-input v-model="BorrowUpdate.bid" autocomplete="off" />
      </el-form-item>

      <el-form-item label="借出日期" label-width="20%">
        <el-input v-model="BorrowUpdate.boout" autocomplete="off" />
      </el-form-item>

      <el-form-item label="归还日期" label-width="20%">
        <el-input v-model="BorrowUpdate.bostill" autocomplete="off" />
      </el-form-item>

      <el-form-item label="押金" label-width="20%">
        <el-input v-model="BorrowUpdate.bodeposit" autocomplete="off" />
      </el-form-item>

      <el-form-item label="借阅状态" label-width="20%">
        <el-input v-model="BorrowUpdate.bostate" autocomplete="off" />
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateBorrowRemove">取消</el-button>
        <el-button type="primary" @click="updateBorrow();">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--修改借阅记录的对话框结束-->

</template>

<script setup>
import { reactive, ref, computed } from 'vue';
import { ElLoading } from 'element-plus';
import { ElMessage } from 'element-plus';
import { Delete } from '@element-plus/icons-vue';
import borrowApi from '@/api/borrowApi';
import bookApi from '@/api/bookApi';
import adminApi from '@/api/adminApi';
import { useTokenStore } from '@/stores/token';

const tokenStore = useTokenStore();

//获取书籍
const bookList = ref([]);

//计算属性
const headers = computed(() => {
  let token = tokenStore.tokenStr;
  return {
    token
  }
});

// 获取所有用户
const adminList = ref([]);

//获取所有借阅记录
const borrowList = ref([]);

//新增用户 上传图片之前的回调
function beforeAvatarUploadAdd(rawFile) {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片仅支持jpg格式');
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过2M');
    return false
  }
  return true;
}

//修改用户 上传图片之前的回调
function beforeAvatarUploadUpdate(rawFile) {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片仅支持jpg格式');
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过2M');
    return false
  }
  return true;
}

//新增用户 上传图片的地址
const imageUrlAdd = ref("");

//修改用户 上传图片的地址
const imageUrlUpdate = ref("");

//新增用户 成功上传之后的回调
function handleAvatarSuccessAdd(resp, uploadFile) {
  console.log(resp);
  if (resp.code == 10000) {
    ElMessage.success(resp.msg);
    imageUrlAdd.value = "http://localhost:8080/upload/" + resp.data;
    adminAdd.value.aavatar = resp.data;
  }
}

//修改 成功上传之后的回调
function handleAvatarSuccessUpdate(resp, uploadFile) {
  console.log(resp);
  if (resp.code == 10000) {
    ElMessage.success(resp.msg);
    imageUrlUpdate.value = "http://localhost:8080/upload/" + resp.data;
    adminUpdate.value.aavatar = resp.data;
  }
}

//定义方法获取所有借阅的信息
function selectAllbo() {
  borrowApi.selectAll()
    .then(resp => {
      borrowList.value = resp.data;
    });
}

// 定义方法获取所有用户的信息
function selectAll() {
  adminApi.selectAll() // 发送axios的请求到服务器
    .then(resp => {
      adminList.value = resp.data; // 提取 data 属性
    });
}

//定义方法获取所有书籍的信息
function selectAllBook() {
  bookApi.selectAll()
    .then(resp => {
      bookList.value = resp.data;
    });
}

// 定义方法存储用户信息
const adminAdd = ref({
  aavatar: '',
  aname: '',
  aage: '',
  agender: '男',
  acontact: '',
  permissions: '',
});

//定义方法存储借阅表信息
const borrowAdd = ref({
  uid: '',
  bid: '',
  boout: '',
  bostill: '',
  bodeposit: '100',
  bostate: '1'
});

//定义方法存储修改用户信息
const adminUpdate = ref({
  aavatar: '',
  aname: '',
  aage: '',
  agender: '男',
  acontact: '',
  permissions: '',
});

//定义方法存储修改借阅记录信息
const BorrowUpdate = ref({
  uid: '',
  bid: '',
  boout: '',
  bostill: '',
  bodeposit: '100',
  bostate: '1',
  uname: '',
  bname: ''
});

//新增对话框是否显示
const insertAdminShow = ref(false);

//新增借阅记录表对话框是否显示
const insertBorrowShow = ref(false);

//修改对话框是否显示
const updateAdminShow = ref(false);

//修改借阅记录对话框是否显示
const updateBorrowShow = ref(false);

// 定义方法完成用户的添加
function addAdmin() {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中~~~',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  adminApi.insert(adminAdd.value)
    .then(resp => {
      loading.close();
      if (resp.code === 10000) {
        // 弹出成功消息
        ElMessage({
          message: resp.msg,
          type: 'success',
          duration: 1200
        });
        // 隐藏对话框
        insertAdminShow.value = false;
        // 清空对话框中的数据
        adminAdd.value = {
          aavatar: '',
          aname: '',
          aage: '',
          agender: '男',
          acontact: '',
          permissions: '',
        };
        // 刷新表格数据
        selectAll();
      } else {
        // 弹出错误消息
        ElMessage({
          message: resp.msg,
          type: 'error',
          duration: 2000
        });
      }
    })
}

// 定义方法完成借阅表的添加
function BorrowAdd() {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中~~~',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  borrowApi.insert(borrowAdd.value)
    .then(resp => {
      loading.close();
      if (resp.code === 10000) {
        // 弹出成功消息
        ElMessage({
          message: resp.msg,
          type: 'success',
          duration: 1200
        });
        // 隐藏对话框
        insertBorrowShow.value = false;
        // 清空对话框中的数据
        borrowAdd.value = {
          aid: '',
          bid: '',
          boout: '',
          bostill: '',
          bodeposit: '100',
          bostate: '1'
        };
        // 刷新表格数据
        selectAllbo();
      } else {
        // 弹出错误消息
        ElMessage({
          message: resp.msg,
          type: 'error',
          duration: 2000
        });
      }
    })
}

// 定义方法完成用户的修改
function updateAdmin() {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中~~~',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  adminApi.update(adminUpdate.value)
    .then(resp => {
      loading.close();
      console.log('API Response:', resp); // 添加调试信息

      if (resp.code === 10000) {
        // 弹出成功消息
        ElMessage({
          message: resp.msg,
          type: 'success',
          duration: 1200
        });
        // 隐藏对话框
        updateAdminShow.value = false;
        // 清空对话框中的数据
        adminUpdate.value = {
          aavatar: '',
          aname: '',
          aage: '',
          agender: '男',
          acontact: '',
          permissions: '',
        };
        // 刷新表格数据
        selectAll();
      } else {
        // 弹出错误消息
        ElMessage({
          message: resp.msg,
          type: 'error',
          duration: 2000
        });
      }
    })
}

// 定义方法完成借阅表的修改
function updateBorrow() {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中~~~',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  borrowApi.updateborrow1(BorrowUpdate.value)
    .then(resp => {
      loading.close();
      console.log('API Response:', resp); // 添加调试信息

      if (resp.code === 10000) {
        // 弹出成功消息
        ElMessage({
          message: resp.msg,
          type: 'success',
          duration: 1200
        });
        // 隐藏对话框
        updateBorrowShow.value = false;
        // 清空对话框中的数据
        BorrowUpdate.value = {
          aid: '',
          bid: '',
          boout: '',
          bostill: '',
          bodeposit: '100',
          bostate: ''
        };
        // 刷新表格数据
        selectAllbo();
      } else {
        // 弹出错误消息
        ElMessage({
          message: resp.msg,
          type: 'error',
          duration: 2000
        });
      }
    })
}

//在修改中查询所有用户
function showUpdateAdmin(aid) {
  adminApi.selectAid(aid)
    .then(resp => {
      adminUpdate.value = resp.data;
      updateAdminShow.value = true;
      imageUrlUpdate.value = `http://localhost:8080/upload/${adminUpdate.value.aavatar}`;
    });
}

//在修改中查询所有借阅记录
function showUpdateBorrow(boid) {
  borrowApi.selectByBoid(boid)
    .then(resp => {
      BorrowUpdate.value = resp.data;
      updateBorrowShow.value = true;
    });
}

//新增对话框,点击取消按钮后清空数据
function insertAdminRemove() {
  insertAdminShow.value = false;
  adminAdd.value = {
    aavatar: '',
    aname: '',
    aage: '',
    agender: '男',
    acontact: '',
    permissions: ''
  };
}

//新增借阅表对话框,点击取消按钮后清空数据
function insertBorrowRemove() {
  insertBorrowShow.value = false;
  borrowAdd.value = {
    aid: '',
    bid: '',
    boout: '',
    bostill: '',
    bodeposit: '100',
    bostate: '1'
  };
}

//修改对话框,点击取消按钮后清空数据
function updateAdminRemove() {
  updateAdminShow.value = false;
  adminUpdate.value = {
    aavatar: '',
    aname: '',
    aage: '',
    agender: '男',
    acontact: '',
    permissions: ''
  };
}

//修改借阅记录对话框,点击取消按钮后清空数据
function updateBorrowRemove() {
  updateBorrowShow.value = false;
  BorrowUpdate.value = {
    aid: '',
    bid: '',
    boout: '',
    bostill: '',
    bodeposit: '100',
    bostate: '1'
  };
}

//定义方法根据用户id进行删除
function delectByAid(aid) {
  adminApi.delete(aid)
    .then(resp => {
      //判断 - 弹出消息 - 刷新表格
      if (resp.code == 10000) {
        //弹出消息
        ElMessage({
          message: resp.msg,
          type: 'success',
          duration: 1200
        });
        //刷新表格
        selectAll();
      } else {
        //弹出消息
        ElMessage({
          message: resp.msg,
          type: 'error',
          duration: 2000
        });
      }
    });
}

//定义方法根据借阅id进行删除
function delectByBoid(boid) {
  borrowApi.deleteborrow(boid)
    .then(resp => {
      //判断 - 弹出消息 - 刷新表格
      if (resp.code == 10000) {
        //弹出消息
        ElMessage({
          message: resp.msg,
          type: 'success',
          duration: 1200
        });
        //刷新表格
        selectAllbo();
      } else {
        //弹出消息
        ElMessage({
          message: resp.msg,
          type: 'error',
          duration: 2000
        });
      }
    });
}

//刷新
function refreshCurrentPage() {
  const urlParams = new URLSearchParams(window.location.search);
  const currentPage = parseInt(urlParams.get('page')) || 1;
  location.reload();
}

// 调用方法获取借阅表的信息
selectAllbo();
// 调用方法获取用户的信息
selectAll();
</script>
<style scoped>
.el-card {
  border: 1px solid #d3d3d3;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  background-color: #f9f9f9;
}

.el-table {
  background-color: #fff;
}

.el-table th {
  background-color: #e0e0e0;
  color: #333;
}

.el-dialog {
  border: 2px solid #666;
  border-radius: 10px;
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.dialog-footer button {
  margin-right: 10px;
  border-radius: 5px;
  padding: 5px 15px;
}

.dialog-footer button:hover {
  opacity: 0.8;
}

.el-pagination {
  background-color: #f9f9f9;
}

.el-dialog__header {
  background-color: #666;
  color: white;
  padding: 10px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  padding: 10px;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
  background-color: #f0f0f0;
}

.el-button {
  border-radius: 4px;
}

.el-button:hover {
  opacity: 0.8;
}

.el-tag {
  border-radius: 4px;
  padding: 2px 8px;
}

.el-tag.type-primary {
  background-color: #409EFF;
  color: #fff;
}

.el-tag.type-info {
  background-color: #909399;
  color: #fff;
}

.avatar-uploader,
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border: 1px dotted #dcdfe6;
  border-radius: 5px;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>